#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QMainWindow>
#include <QFile>
#include <QTextStream>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include <QtCharts/QChart>
#include <QtCharts/QValueAxis>
#include <random>
#include <fstream>
#include <vector>
#include <iostream>
#include <DspFilters/Dsp.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    buildFile();

    // 1. 读两列
    QFile file("noise_filtered.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning("无法打开 noise_filtered.txt");
        return ;
    }

    QLineSeries *raw     = new QLineSeries();
    QLineSeries *filteredS= new QLineSeries();
    raw->setName("Original");
    filteredS->setName("Filtered");

    QTextStream in(&file);
    int idx = 0;
    while (!in.atEnd()) {
        QStringList l = in.readLine().split(' ', Qt::SkipEmptyParts);
        if (l.size() != 2) continue;
        qreal x = idx++;
        raw->append(x, l[0].toDouble());
        filteredS->append(x, l[1].toDouble());
    }

    // 2. 一张图里放两条曲线
    QChart *chart = new QChart();
    chart->addSeries(raw);
    chart->addSeries(filteredS);
    chart->createDefaultAxes();          // 自动计算坐标轴范围
    chart->setTitle("Gaussian Noise vs. 4-order Bessel LPF");

    // 3. 视图
    QChartView *view = new QChartView(chart);
    view->setRenderHint(QPainter::Antialiasing);

    // 4. 主窗口
    setCentralWidget(view);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::buildFile()
{
    const int   numSamples = 48000;      // 1 秒
    const float sampleRate = 48000.0f;
    const float cutoffFreq = 1000.0f;

    // 1. 生成高斯白噪声
    std::mt19937 rng(42);
    std::normal_distribution<float> dist(0.0f, 0.2f);

    std::vector<float> original(numSamples);
    for (auto& s : original) s = dist(rng);

    // 2. 复制一份给滤波器做“就地”处理
    std::vector<float> filtered = original;   // 拷贝

    // 3. 配置 4 阶 Bessel 低通滤波器
    Dsp::SimpleFilter<Dsp::Bessel::LowPass<4>, 1> f;
    f.setup(4, sampleRate, cutoffFreq);

    // 4. 滤波
    float* channels[1] = { filtered.data() };
    f.process(numSamples, channels);

    // 5. 写入文件：第一列原始，第二列滤波后
    std::ofstream ofs("noise_filtered.txt");
    if (!ofs) {
        std::cerr << "无法打开文件 noise_filtered.txt\n";
        return;
    }
    for (size_t i = 0; i < original.size(); ++i) {
        ofs << original[i] << ' ' << filtered[i] << '\n';
    }

}
